package com.koi.satoken.service.loginlog;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koi.common.enums.log.ClientType;
import com.koi.common.utils.ip.IpAddressUtil;
import com.koi.common.utils.ip.IpUtil;
import com.koi.common.utils.ip.ServletUtil;
import com.koi.plus.mapper.system.SysLoginLogMapper;
import com.koi.pojo.system.SysLoginLog;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author ･ᴗ･
 * @description [SysLoginLogServiceImpl]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SaLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements SaLoginLogService {

    private final IpAddressUtil ipAddressUtil;

    /**
     * @description [保存登录日志]
     * @author ･ᴗ･
     */
    @Override
    public void addLoginLog(String loginName, String loginStatus, String message) {
        // 1、new一个登录日志对象，用来装载信息
        SysLoginLog sysLoginLog = new SysLoginLog();
        try {
            sysLoginLog.setLoginName(loginName);
            sysLoginLog.setLoginStatus(loginStatus);
            // LocalDateTime.now() 时间类型为 LocalDateTime类型
            sysLoginLog.setLoginTime(new Date());
            sysLoginLog.setMessage(message);
            // 2、登录IP地址
            sysLoginLog.setIpAddress(IpUtil.getIpAddr(ServletUtil.getRequest()));
            // 3、登录地理位置
            sysLoginLog.setLoginAddress(ipAddressUtil.getAddress(sysLoginLog.getIpAddress()));
            // 4、UserAgent信息
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtil.getRequest().getHeader("User-Agent"));
            // 5、登录浏览器
            sysLoginLog.setBrowser(userAgent.getBrowser().getName());
            // 6、登录操作系统
            sysLoginLog.setOs(userAgent.getOperatingSystem().getName());
            // 7、登录设备
            String deviceName = userAgent.getOperatingSystem().getDeviceType().getName();
            if (StringUtils.isBlank(deviceName)) {
                deviceName = "Default";
            } else if ("Computer".equals(deviceName)) {
                deviceName = ClientType.PC.name();
            } else if ("Mobile".equals(deviceName)) {
                deviceName = ClientType.MOBILE.name();
            }
            sysLoginLog.setDeviceName(deviceName);
        } catch (Exception e) {
            sysLoginLog.setMessage(e.getMessage());
            sysLoginLog.setLoginStatus("1");
            log.error("登录日志异常信息：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            // 8、登录日志保存
            this.save(sysLoginLog);
        }

    }

}
